<?php
namespace App\Service;

class Ctr
{
    public static function getBestFromKLog($adPostionId, $identifiers)
    {
    	\Log::info("getBestFromKLog");
    	$cpmDate = date('Ymd');
    	$cpmHour = date('H');
    	$cpmInterval = intval(date('i') / 5);
    	$providers = \App\Model\AdProvider::whereIn('identifier', $identifiers)->get();
    	$bestCpm = \App\Model\Cpm::where('cpm_date', $cpmDate)
    						 ->where('cpm_hour', $cpmHour)
    						 // ->where('cpm_interval', $cpmInterval)
    						 ->where('ad_position_id', $adPostionId)
    						 ->whereIn('ad_provider_id', $providers->pluck('id')->toArray())
    						 ->where('ctr_val', '!=', -1)
    						 ->orderBy('cpm_val', 'desc')
    						 ->first();
    	$trailCpms = \App\Model\Cpm::getTrailCpm(3, $cpmDate, $cpmHour);
    	if (!empty($bestCpm)) {
    		if (empty($trailCpms)) {
    			$bestProviderId = $bestCpm->ad_provider_id;
    		} else {
    			$trailBestCpm = $trailCpms->sortByDesc('trail_cpm_val')->first();
    			if ($bestCpm->cpm_val < $trailBestCpm->trail_cpm_val) {
    				$bestProviderId = $trailBestCpm->ad_provider_id;
    			} else {
    				$bestProviderId = $bestCpm->ad_provider_id;
    			}
    		}
   			$provider = $providers->where('id', $bestCpm->ad_provider_id)->first();
			$identifier = $provider->identifier;
    	} else {
	        $key = array_rand($identifiers);
	        $identifier = $identifiers[$key];
    	}
    	return $identifier;
    }
}